const { AVATAR_PATH } = require("../config/path");
const fileService = require("../service/file.service");
const fs = require("fs");
const os = require("os");
const profileService = require("../service/profile.service");

class FileController {
  // 上传头像
  async createAvatar(ctx, next) {
    const id = ctx.user.id;
    const res = await fileService.findAvatarByUserId(id);
    // 如果已经过上传头像
    if (res) {
      try {
        fs.unlinkSync(`${AVATAR_PATH}/${res.filename}`);
        await fileService.updateAvatar(ctx);
      } catch (err) {
        console.log(err);
      }
    } else {
      await fileService.insertAvatar(ctx);
    }
    // 时间戳
    const timestampUnix = Date.now().toString();
    // 保存头像地址
    const baseUrl =
      os.hostname() === "greenteck"
        ? "http://localhost:3004"
        : "http://47.108.24.123:3004";
    const avatarUrl = `${baseUrl}/file/avatar/${id}/${timestampUnix}`;
    await profileService.updateUserAvatar(avatarUrl, id);

    ctx.body = {
      status: 201,
      message: "上传头像成功",
      avatarUrl,
    };
  }
  // 查看头像
  async showAvatar(ctx, next) {
    const { id } = ctx.params;
    // 查询头像信息
    const res = await fileService.findAvatarByUserId(id);
    const { filename, mimetype } = res;
    ctx.type = mimetype;
    ctx.body = fs.createReadStream(`${AVATAR_PATH}/${filename}`);
  }
}

module.exports = new FileController();
